package com.my.lucky.controller;

import com.my.lucky.config.IwencaiConfig;
import com.my.lucky.entity.StockLimitUp;
import com.my.lucky.model.ReviewInfo;
import com.my.lucky.repository.ReviewInfoRepository;
import com.my.lucky.service.GaiNianInfoService;
import com.my.lucky.service.StockLimitUpService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDate;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * 涨停数据查询控制器
 */
@Slf4j
@Controller
@RequestMapping("/limitup")
public class StockLimitUpController {

    @Autowired
    private StockLimitUpService stockLimitUpService;

    @Autowired
    private GaiNianInfoService gaiNianInfoService;

    @Autowired
    private ReviewInfoRepository reviewInfoRepository;;

    @Autowired
    private IwencaiConfig iwencaiConfig;

//    public static Map<String, Long> countConcepts(List<StockLimitUp> pageContent) {
//        if (pageContent == null) {
//            return Collections.emptyMap();
//        }
//        return pageContent.stream()
//                .filter(Objects::nonNull)
//                .map(result -> {
////                    String concept = result.getConcept() != null ? result.getConcept() : "";
//                    String allConcept = result.getGainians() != null ? result.getGainians() : "";
////                    return concept + "," + allConcept;
//                    return allConcept;
//                })
//                .filter(str -> !str.isEmpty())
//                .flatMap(str -> Arrays.stream(str.split(";")))
//                .filter(concept -> !concept.trim().isEmpty())
//                .collect(Collectors.groupingBy(
//                        String::trim,
//                        Collectors.counting()
//                ));
//    }


    public static Map<String, Long> countConcepts(List<StockLimitUp> pageContent) {
        if (pageContent == null) {
            return Collections.emptyMap();
        }
        return pageContent.stream()
                .filter(Objects::nonNull) // 过滤null的StockLimitUp对象
                .map(result -> {
                    // 直接获取原始概念字符串（不做trim，保留原始内容）
                    String allConcept = result.getGainians();
                    // 若概念为null，用空字符串处理（避免NPE）
                    return allConcept != null ? allConcept : "";
                })
                .filter(str -> !str.isEmpty()) // 过滤空字符串（严格匹配，不trim）
                .flatMap(str -> {
                    // 按分号分割，保留原始分割结果（包括前后空格）
                    String[] concepts = str.split(";");
                    return Arrays.stream(concepts);
                })
                .filter(concept -> !concept.isEmpty()) // 过滤分割后产生的空字符串（严格匹配）
                .collect(Collectors.groupingBy(
                        Function.identity(), // 用原始字符串作为key（精确匹配，不做任何处理）
                        Collectors.counting() // 统计出现次数
                ));
    }

    public String getSortedConceptCounts(List<StockLimitUp> pageContent) {
        Map<String, Long> conceptCounts = countConcepts(pageContent);
        // 按Value降序排序
        List<Map.Entry<String, Long>> sortedEntries = conceptCounts.entrySet().stream()
                .sorted(Map.Entry.<String, Long>comparingByValue().reversed())
                .collect(Collectors.toList());
        // 格式化输出
        StringBuilder sb = new StringBuilder();
        for (Map.Entry<String, Long> entry : sortedEntries) {
            if (entry.getValue() > 1
            && iwencaiConfig.getSunstocks()!=null && iwencaiConfig.getSunstocks().get(entry.getKey())!=null && iwencaiConfig.getSunstocks().get(entry.getKey())>0 ) {  //概念有个股
                sb.append(entry.getKey())
                        .append("[")
                        .append(entry.getValue())
                        .append("]")
                        .append(";");
            }
        }
        return sb.toString();
    }

    /**
     * 概念存在
     * @param pageContent
     * @return
     */
    public List<StockLimitUp> getGaiNianNotNull(List<StockLimitUp> pageContent) {
        List<StockLimitUp> cheLimits = new ArrayList<>();
        if (pageContent!=null){
//            Map<String, Long> conceptCounts = countConcepts(pageContent);
//            System.out.println("iwencaiConfig.getSunstocks()=="+iwencaiConfig.getSunstocks());
            for (int i = 0; i < pageContent.size(); i++) {
                StockLimitUp limitUp = pageContent.get(i);
                if (limitUp !=null && limitUp.getLimitUpReason()!=null) {  //概念有个股
                    // 格式化输出
                    String[] reasons = limitUp.getLimitUpReason().split("\\+");
                    StringBuilder sb = new StringBuilder();
                    for (int j = 0; j < reasons.length; j++) {
                        if (iwencaiConfig.getSunstocks()!=null
                                && iwencaiConfig.getSunstocks().get(reasons[j])!=null
                                && iwencaiConfig.getSunstocks().get(reasons[j])>0 ) {  //概念有个股
                            sb.append(reasons[j]).append("+");
                        }
                    }
                    limitUp.setLimitUpReasonGai(sb.toString());
                    cheLimits.add(limitUp);
                }
            }
        }
        return cheLimits;
    }

    /**
     * 涨停查询页面
     */
    @GetMapping("/search")
    public String searchPage() {
        return "limitup/search";
    }

    /**
     * 查询涨停数据API
     */
    @GetMapping("/api/search")
    @ResponseBody
    public Map<String, Object> searchLimitUpStocks(
            @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate startDate,
            @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate endDate,
            @RequestParam(required = false) String stockCodeOrName,
            @RequestParam(required = false) String consecutiveDays,
            @RequestParam(required = false) String gainian,
            @RequestParam(required = false) String limitUpType,
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "20") int size,
            @RequestParam(defaultValue = "recordTime") String sortField,
            @RequestParam(defaultValue = "asc") String sortDirection) {
        try {
            Page<StockLimitUp> result = stockLimitUpService.searchLimitUpStocks(
                    startDate, endDate, stockCodeOrName, consecutiveDays, gainian, limitUpType,
                    page, size, sortField, sortDirection);

            String allGainian = getSortedConceptCounts(result.getContent());

//            System.out.println("searchLimitUpStocks allGainian=="+allGainian);
//            System.out.println("allGainian=="+allGainian);

            LocalDate today = LocalDate.now();
//            LocalDate today = LocalDate.now().minusDays(1);

            ReviewInfo reviewInfo = reviewInfoRepository.findFirstByReviewTime(today);
            List<StockLimitUp> cheLimits = getGaiNianNotNull(result.getContent());

            Map<String, Object> response = new HashMap<>();
            response.put("success", true);
            response.put("data", cheLimits);
            response.put("allGainian", allGainian);
            if (reviewInfo!=null) {
                response.put("revGainian", reviewInfo.getReviewGainian());
            }
            response.put("totalElements", result.getTotalElements());
            response.put("totalPages", result.getTotalPages());
            response.put("currentPage", result.getNumber());
            response.put("pageSize", 500);
            response.put("hasNext", result.hasNext());
            response.put("hasPrevious", result.hasPrevious());
            response.put("flowStock", iwencaiConfig.getFocus());
            response.put("flowGainian", iwencaiConfig.getFocusGaiNian());
            response.put("allOptional", iwencaiConfig.getAllOptional());
            return response;
        } catch (Exception e) {
            log.error("查询涨停数据失败", e);
            Map<String, Object> response = new HashMap<>();
            response.put("success", false);
            response.put("message", "查询失败: " + e.getMessage());
            return response;
        }
    }

    /**
     * 获取今日涨停股票
     */
    @GetMapping("/api/today")
    @ResponseBody
    public Map<String, Object> getTodayLimitUpStocks() {
        try {
            List<StockLimitUp> stocks = stockLimitUpService.getTodayLimitUpStocks();
            String allGainian = getSortedConceptCounts(stocks);

//            System.out.println("getTodayLimitUpStocks allGainian=="+stocks.size()+"====="+allGainian);
            LocalDate today = LocalDate.now();
//            LocalDate today = LocalDate.now().minusDays(1);

            ReviewInfo reviewInfo = reviewInfoRepository.findFirstByReviewTime(today);
//            System.out.println(allGainian);
            Map<String, Object> response = new HashMap<>();
            response.put("success", true);
            response.put("allGainian", allGainian);
            if (reviewInfo!=null) {
                response.put("revGainian", reviewInfo.getReviewGainian());
            }
            response.put("data", stocks);
            response.put("count", stocks.size());
            response.put("pageSize", 500);
            response.put("flowStock", iwencaiConfig.getFocus());
            response.put("flowGainian", iwencaiConfig.getFocusGaiNian());
            response.put("allOptional", iwencaiConfig.getAllOptional());
//            System.out.println("==iwencaiConfig.getFocus()=="+iwencaiConfig.getFocus());
            return response;
        } catch (Exception e) {
            log.error("获取今日涨停数据失败", e);
            Map<String, Object> response = new HashMap<>();
            response.put("success", false);
            response.put("message", "获取失败: " + e.getMessage());
            return response;
        }
    }

    /**
     * 获取涨停类型选项
     */
    @GetMapping("/api/types")
    @ResponseBody
    public Map<String, Object> getLimitUpTypes() {
        try {
            List<String> types = stockLimitUpService.getAllLimitUpTypes();
            Map<String, Object> response = new HashMap<>();
            response.put("success", true);
            response.put("data", types);
            return response;
        } catch (Exception e) {
            log.error("获取涨停类型失败", e);
            Map<String, Object> response = new HashMap<>();
            response.put("success", false);
            response.put("message", "获取失败: " + e.getMessage());
            return response;
        }
    }

    /**
     * 获取几天几板选项
     */
    @GetMapping("/api/consecutive-days")
    @ResponseBody
    public Map<String, Object> getConsecutiveDaysOptions() {
        try {
            List<String> options = stockLimitUpService.getAllConsecutiveDaysOptions();
            Map<String, Object> response = new HashMap<>();
            response.put("success", true);
            response.put("data", options);
            return response;
        } catch (Exception e) {
            log.error("获取几天几板选项失败", e);
            Map<String, Object> response = new HashMap<>();
            response.put("success", false);
            response.put("message", "获取失败: " + e.getMessage());
            return response;
        }
    }

    /**
     * 根据股票代码查询历史涨停记录
     */
    @GetMapping("/api/history/{stockCode}")
    @ResponseBody
    public Map<String, Object> getStockLimitUpHistory(@PathVariable String stockCode) {
        try {
            List<StockLimitUp> history = stockLimitUpService.getStockLimitUpHistory(stockCode);
            Map<String, Object> response = new HashMap<>();
            response.put("success", true);
            response.put("data", history);
            response.put("count", history.size());
            return response;
        } catch (Exception e) {
            log.error("查询股票历史涨停记录失败", e);
            Map<String, Object> response = new HashMap<>();
            response.put("success", false);
            response.put("message", "查询失败: " + e.getMessage());
            return response;
        }
    }

    /**
     * 统计指定日期的涨停股票数量
     */
    @GetMapping("/api/count")
    @ResponseBody
    public Map<String, Object> countLimitUpStocks(
            @RequestParam @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate date) {
        try {
            Long count = stockLimitUpService.countLimitUpStocksByDate(date);
            Map<String, Object> response = new HashMap<>();
            response.put("success", true);
            response.put("count", count);
            response.put("date", date.toString());
            return response;
        } catch (Exception e) {
            log.error("统计涨停股票数量失败", e);
            Map<String, Object> response = new HashMap<>();
            response.put("success", false);
            response.put("message", "统计失败: " + e.getMessage());
            return response;
        }
    }
} 